<?php

namespace Microcyan\ModelX\Providers;

use GuzzleHttp\Client;
use Psr\Http\Message\StreamInterface;

class Http
{
    protected $client;
    protected $apiKey;
    protected $baseUri;
    protected $options=[];

    public function __construct($base_uri="https://api.openai.com"){
        $this->baseUri = $base_uri;
        $this->client = new Client(['base_uri'=>$this->baseUri ]);
    }

    public function post($data,$isStream=false,$url="/v1/chat/completions"){
        $options = $this->getOptions($data,$isStream);
        $resp = $this->client->post($url,$options)->getBody()->getContents();
        $resp = @json_decode($resp,true);
        if (empty($resp) || !is_array($resp)) $resp=[];
        return $resp;
    }


    private function getOptions($data,$isStream=false){
        $options = $this->options;
        if (!is_array($options))$options = [];
        //更新body
        $data['stream'] = $isStream;
        $options['body'] = json_encode($data);
        //更新headers
        if (!isset($options['headers']))$options['headers']=[];
        $options['headers']['Content-Type']='application/json';
        $options['headers']['Authorization']="Bearer {$this->apiKey}";
        if ($isStream)$options['headers']['X-DashScope-SSE'] = 'enable';
        $options['stream'] = $isStream;
        return $options;
    }


    public function withOptions($options){
        $this->options = $options;
        return $this;
    }
    public function withApiKey($key){
        $this->apiKey = $key;
        return $this;
    }

}